<?php
/**
* SocialEngine
*
* @category   Application_Extensions
* @package    Flashgame
* @copyright 2010 YouNet
*/

/**
* @category   Application_Extensions
* @package    Flashgame
* @copyright 2010 YouNet
*/
class Flashgame_AdminPackageController extends Core_Controller_Action_Admin
{
    public function indexAction()
    {
        $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')
        ->getNavigation('flashgame_admin_main', array(), 'flashgame_admin_main_package'); 
        $this->view->packages = Engine_Api::_()->flashgame()->getPackages();
        $this->view->form = $form = new Flashgame_Form_Admin_Global();

        /*
        if( $this->getRequest()->isPost()&& $form->isValid($this->getRequest()->getPost()))
        {
        $values = $form->getValues();

        foreach ($values as $key => $value){
        Engine_Api::_()->getApi('packages', 'core')->setSetting($key, $value);
        }

        } 
       
        $table = Engine_Api::_()->getDbtable('levels', 'authorization');
        $select = $table->select();
        $user_levels = $table->fetchAll($select);
      
        foreach ($user_levels as $user_level){
        $levels_prepared[$user_level->level_id]= $user_level->getTitle();
        }
        */  
        //$this->view->user_levels = $user_levels;
    }
    public function packageusersAction()
    {
        $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')
        ->getNavigation('flashgame_admin_main', array(), 'flashgame_admin_main_package'); 

        $this->view->packageusers = $packageusers = Engine_Api::_()->flashgame()->getPackageUsers($this->_getParam("package_id"));

        $tablePackage = Engine_Api::_()->getDbtable('packages', 'flashgame');
        $selectPackage = $tablePackage->select()->where('package_id = ?', $this->_getParam("package_id"));;
        $this->view->package = $package = $tablePackage->fetchRow($selectPackage);

        // Get level 
        $table = Engine_Api::_()->getDbtable('levels', 'authorization');
        $select = $table->select();
        $user_levels = $table->fetchAll($select);
        $this->view->user_levels = $user_levels;

    }  
    public function editAction()
    {
        $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')
        ->getNavigation('flashgame_admin_main', array(), 'flashgame_admin_main_package');     
        $this->view->flashgame = $flashgame = Engine_Api::_()->getItem('flashgame', $this->_getParam('flashgame_id'));

        $table = Engine_Api::_()->getDbtable('packages', 'flashgame');
        $select = $table->select()->where('package_id = ?', $this->_getParam("package_id"));;
        $package = $table->fetchRow($select);

        $this->view->form = $form = new Flashgame_Form_Admin_Package_Edit(array(
        'item' => $package
        )); 

        if ($this->getRequest()->isPost())
        {
            $values = $this->getRequest()->getPost();
           
            if ($values['package_period'] < 1)
            {
                $form->addError(Zend_Registry::get('Zend_Translate')->_('Period must more than 0.'));
                return;
            }
          
            if ($values['package_price'] < 1)
            {
                $form->addError(Zend_Registry::get('Zend_Translate')->_('Price must more than 0.'));
                return;
            }
            $validator = new Zend_Validate_Int();
            if (!($validator->isValid($values['package_period']))) 
            {
            	//print_r($values['package_period']);die; 
            	$form->addError(Zend_Registry::get('Zend_Translate')->_('Please enter valid number in Period.'));
            	return;
            }
          	$validatorfloat = new Zend_Validate_Float();
            if (!($validatorfloat->isValid($values['package_price']))) 
            {
            	$form->addError(Zend_Registry::get('Zend_Translate')->_('Please enter valid number in Price.'));
            	return;
            }
                    
            $db = Engine_Db_Table::getDefaultAdapter();
            $db->beginTransaction();
            try
            {
                $package->setFromArray($values);
                
                $package->save();
                $db->commit();
                return $this->_redirect("admin/flashgame/package");
            }
            catch( Exception $e )
            {
                $db->rollBack();
                throw $e;
            }
        }


    }
    public function enableAction()
    {
        if( !$this->_helper->requireUser()->isValid() ) return;
        $viewer = Engine_Api::_()->user()->getViewer();

        $table = Engine_Api::_()->getDbtable('packages', 'flashgame');
        $select = $table->select()->where('package_id = ?', $this->_getParam("package_id"));;
        $package = $table->fetchRow($select);

        $db = $table->getAdapter();
        $db->beginTransaction();
        try
        {
            $package->package_enabled = $this->_getParam('enable');
            $package->save();

            $db->commit();
        }

        catch( Exception $e )
        {
            $db->rollBack();
            throw $e;
        }
        return $this->_redirect("admin/flashgame/package");
    }
    public function usereditAction()
    {
        $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')
        ->getNavigation('flashgame_admin_main', array(), 'flashgame_admin_main_package');     

        $this->view->package_id = $package_id = $this->_getParam("package_id");

        // Get User
        $tableUser = Engine_Api::_()->getDbtable('users', 'user');
        $selectUser = $tableUser->select()->where('user_id = ?', $this->_getParam("user_id"));
        $this->view->puser = $puser = $tableUser->fetchRow($selectUser);

        $this->view->packages = Engine_Api::_()->flashgame()->getEnablePackagesToUpgrade($this->_getParam("user_id"));

        // Get package
        $table = Engine_Api::_()->getDbtable('packages', 'flashgame');
        $select = $table->select()->where('package_id = ?', $this->_getParam("package_id"));
        $package = $table->fetchRow($select);

        // Get User package
        $tableuserp = Engine_Api::_()->getDbtable('userpackages', 'flashgame');
        $selectuserp = $tableuserp->select()
        ->where('userpackage_user_id = ?', $this->_getParam("user_id"))
        ->where('userpackage_package_id = ?', $this->_getParam("package_id"));

        $userpackage = $tableuserp->fetchRow($selectuserp);

        $userpackage = Engine_Api::_()->flashgame()->getPackageUser($this->_getParam("package_id"),$this->_getParam("user_id"));
        if ($this->getRequest()->isPost())
        {
            // handle save for tags
            $values = $this->getRequest()->getPost();   
            $db = Engine_Db_Table::getDefaultAdapter();
            $db->beginTransaction();
            try
            {
                // update user old packge
                $package->package_sold = (int) $package->package_sold - 1;
                $package->save();

                // update user  package
                $userpackage->userpackage_package_id = (int) $values["package_id"];
                $userpackage->save();

                // update user new packge          
                // Get package

                $tablenew = Engine_Api::_()->getDbtable('packages', 'flashgame');
                $selectnew = $tablenew->select()->where('package_id = ?', $values["package_id"]);
                $packagenew = $tablenew->fetchRow($selectnew);
                $packagenew->package_sold = (int) $packagenew->package_sold + 1;
                $packagenew->save();

                $db->commit();

                $this->_forward('success', 'utility', 'core', array(
                'smoothboxClose' => 10,
                'parentRefresh'=> 10,
                'messages' => array('Update successful.')
                ));
                //return $this->_redirect("admin/flashgame/packageusers/".$package_id);
            }
            catch( Exception $e )
            {
                $db->rollBack();
                throw $e;
            }
        }


    }
    //packageuserdelete
    public function userdeleteAction()
    {
        // In smoothbox
        $this->_helper->layout->setLayout('admin-simple');
        $package_id = $this->_getParam('package_id');
        $user_id = $this->_getParam('user_id');
        $this->view->package_id=$package_id;
        $this->view->user_id=$user_id;
        // Check post
        if( $this->getRequest()->isPost())
        {
            $db = Engine_Db_Table::getDefaultAdapter();
            $db->beginTransaction();
            try
            {
                $row = Engine_Api::_()->flashgame()->getPackageUser($package_id,$user_id);
                // delete the flashgame category in the database
                $row->delete();
                $table = Engine_Api::_()->getDbtable('packages', 'flashgame');
                $select = $table->select()->where('package_id = ?', $package_id);;
                $package = $table->fetchRow($select);
                $package->package_sold = $package->package_sold-1;
                $package->save();

                // get default level to downgrade user level
                $default_level = Engine_Api::_()->getItemTable('authorization_level')->getDefaultLevel();
                $Utable = Engine_Api::_()->getDbtable('users', 'user');
                $Uselect = $Utable->select()->where('user_id = ?', $user_id);;
                $UserToDowngrade = $Utable->fetchRow($Uselect);
                $UserToDowngrade->level_id = $default_level->level_id;
                $UserToDowngrade->save();
                $db->commit();
            }

            catch( Exception $e )
            {
                $db->rollBack();
                throw $e;
            }
            $this->_forward('success', 'utility', 'core', array(
            'smoothboxClose' => 10,
            'parentRefresh'=> 10,
            'messages' => array('')
            ));
        }

        // Output
        $this->renderScript('admin-package/userdelete.tpl');
    }


    public function deleteAction()
    {
        // In smoothbox
        $this->_helper->layout->setLayout('admin-simple');
        $package_id = $this->_getParam('package_id');
        $this->view->package_id=$package_id;
        // Check post
        if( $this->getRequest()->isPost())
        {
            $db = Engine_Db_Table::getDefaultAdapter();
            $db->beginTransaction();

            try
            {
                $row = Engine_Api::_()->flashgame()->getPackage($package_id);

                // delete the flashgame category in the database
                $row->delete();

                $db->commit();
            }

            catch( Exception $e )
            {
                $db->rollBack();
                throw $e;
            }
            $this->_forward('success', 'utility', 'core', array(
            'smoothboxClose' => 10,
            'parentRefresh'=> 10,
            'messages' => array('')
            ));
        }

        // Output
        $this->renderScript('admin-package/delete.tpl');
    }
    public function viewAction()
    {

        $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')
        ->getNavigation('flashgame_admin_main', array(), 'flashgame_admin_main_package');
        $packageTable = Engine_Api::_()->getDbtable('packages', 'flashgame');
        $select = $packageTable->select()->where('package_id = ?', $this->_getParam("package_id"));
        $this->view->packages = $packageTable->fetchAll($select);

        $table = Engine_Api::_()->getDbtable('levels', 'authorization');
        $select = $table->select();
        $user_levels = $table->fetchAll($select);
        $this->view->user_levels = $user_levels; 
        $this->view->periodtypes = Engine_Api::_()->flashgame()->getPeriodtypes(); 
    }  

    public function createAction()
    {
        $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')
        ->getNavigation('flashgame_admin_main', array(), 'flashgame_admin_main_package'); 
        $this->view->form = $form = new Flashgame_Form_Admin_Package();

        // If not post or form not valid, return
        if( $this->getRequest()->isPost() && $form->isValid($this->getRequest()->getPost()) )
        {
            $table = Engine_Api::_()->getItemTable('flashgame');
            $db = $table->getAdapter();
            $db->beginTransaction();
            $values = $form->getValues();
            if ($values['package_period'] < 1)
            {
                $form->addError(Zend_Registry::get('Zend_Translate')->_('Period must more than 0.'));
                return;
            }
          
            if ($values['package_price'] < 1)
            {
                $form->addError(Zend_Registry::get('Zend_Translate')->_('Price must more than 0.'));
                return;
            }
            try
            { 
                $packageTable = Engine_Api::_()->getDbtable('packages', 'flashgame');
                $packageTable->createRow()->setFromArray(array(
                /*'package_level_id' => $values['package_level_id'],
                'package_downgrade_level_id' => $values['package_downgrade_level_id'],
                */
                'package_name' => $values['package_name'],
                'package_description' => $values['package_description'],
                'package_period' => $values['package_period'],
                'package_periodtype' => $values['package_periodtype'],
                'package_price' => $values['package_price'],
                /*'package_onetime_price' => $values['package_onetime_price'],*/
                'package_enabled' => $values['package_enabled'],
                'package_recurring' => $values['package_recurring'],
                'package_recurring_cycles' => $values['package_recurring_cycles']
                ))->save();        
                // Commit
                $db->commit();
                // Redirect
                return $this->_redirect("admin/flashgame/package"); 
            }

            catch( Exception $e )
            {
                $db->rollBack();
                throw $e;
            }
        }
    }  

}